import { Injectable,Inject, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
// import * as jwt from 'jsonwebtoken'; // 假设使用 JWT 进行身份验证
// import { WEB_SALE_VALUE } from '../config/constant';
// import * as crypto from 'crypto-js';
//查找省

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
//  constructor(@Inject(CustomLogger) private loggerService: CustomLogger) {}

  private logger = new Logger('HTTP');
  use(req: Request, res: Response, next: NextFunction) {
    const { ip, method, originalUrl } = req;
    const userAgent = req.get('user-agent') || '';
    // const user = this.jwt.handleRequest(req, res);
    // console.log(user)

    res.on('finish',async () => {
      const token = req.headers['authorization']?.split(' ')[1]; // 假设 token 在 Authorization header 中
      console.log('token:', token)
      const userId = req.user || null;
      const { statusCode, } = res;
      const contentLength = res.get('content-length');

        if (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') {
          this.logger.log(`userId:${JSON.stringify( userId)}; method:${method}  ;api:${originalUrl};code:${statusCode}  ; Body: ${JSON.stringify(req.body)} ; contentLength:${contentLength}  ;userAgent:${userAgent} ;ip:${ip}`);
        } else if (req.method === 'GET') {
            this.logger.log(`userId:${JSON.stringify( userId)}; method:${method};api:${originalUrl};Query: ${JSON.stringify(req.query)};statusCode:${statusCode} contentLength:${contentLength} - ${userAgent} ;ip:${ip}`);
        }

    });
    next();
  }
}
